<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
* magento 类
*/
class Magento_m extends CI_Model
{
	
	function __construct()
	{
		parent::__construct();
	}

//获取sql语句
public function sponsorindexdisplaytpl($where='*',$value='*',$mstype='*',$purpose='*',$starttime='*',$endtime='*',$ms_status='*'){
    $sql="select * from `db_magento_sponsor`";
    if(    $where != '*' 
    	|| $mstype != '*' 
    	|| $purpose != '*'
    	|| $starttime != '*'
    	|| $endtime != '*'
    	|| $ms_status != '*'){
    $sql.=" WHERE";
        if($where != '*') $sql .= " $where like '%{$value}%' AND";
        if($mstype != '*') $sql .= " `ms_type` = '{$mstype}' AND";
        if($purpose != '*') $sql .= " `ms_purpose` = '{$purpose}' AND";
        if($starttime != '*') $sql .= " `ms_creat_time` >= '{$starttime}' AND";
        if($endtime != '*') $sql .= " `ms_creat_time` <= '{$endtime}' AND";
        if($ms_status != '*') $sql .= " `ms_status`='{$ms_status}' AND";
        $sql .= " `ms_creat_time` != ''";
    }
    
    return $sql;
}

//执行sql
public function getindextpl($sql,$page){
    $num = 30*($page - 1);
	$sql .= " ORDER BY `ms_id` DESC LIMIT $num,30;";
    return $this->db->query($sql)->result_array();
}

//获取总数
public function sqlcount($sql){
 $list=$this->db->query($sql)->result_array();
 return count($list);
}


//删除赞助
public function sponsordelect($id){
	$sql="delete from db_magento_sponsor where ms_id='{$id}';";
	$this->db->query($sql);
}

//修改赞助
public function sponsorlist($id){
 $sql="select * from db_magento_sponsor where ms_id='{$id}';";
return $this->db->query($sql)->result_array();
}

//保存赞助信息
public function savesponsor($intojson){
$into=json_decode($intojson,true);
$intoarr=array();
foreach ($into as $key => $value) {
	$intoarr[$key]=addslashes($value);
}
$intoarr['ms_income_currency']=$intoarr['ms_object_money_sign'];
$intoarr['ms_status']='1';
$intoarr['ms_is_sendemail']='0';
$intoarr['ms_user']=$_COOKIE["username"];
$intoarr['ms_creat_time']=date('Y-m-d H:i:s');
$intoarr['ms_product_china_name']=$this->getproductname($into['ms_product_info']);
 $this->db->insert("db_magento_sponsor",$intoarr);

}

public function getproductname($info){
$p1=explode('+', $info);
$skuarr=array();
foreach ($p1 as $value) {
	// if(strpos($va,',') === false){
 //     $skuarr[]=$value;
	// }else{
	unset($p2);
	$p2=explode(',', $value);
	$skuarr[]=$p2[0];
	// }
}
$name='';
foreach ($skuarr as $sku) {
  $rgoods = $this->db->get_where("db_goods","goods_sku='".$sku."'")->result_array();
  if(isset($rgoods[0]["goods_id"]))
  {
  $name.=$rgoods[0]['goods_name'].',';
  }
}
return $name;

}

public function sponsorupdata($intojson,$id){
	$into=json_decode($intojson,true);
	//print_r($into);
	$into['ms_product_china_name']=$this->getproductname($into['ms_product_info']);
	$this->db->update('db_magento_sponsor',$into,"ms_id='".$id."'");
}

//uploadcsv 上传赞助数据
public function uploadcsv($data,$ms_income_currency,$timedata){
  //根据货币单位查询出来汇率
 $exchange=$this->db->get_where("d_moneyrate","name='{$ms_income_currency}'")->result_array();
 if ($exchange[0]["rate"])
 	$exchangerate=$exchange[0]["rate"];
 else
 	$exchangerate=1;
 //循环读取数据，
foreach ($data as $value) {
 	//判断首列，如果首列为空，则跳过
 	if(is_null($value[0])) continue;
 	//如果第一个值有的话，则根据第一个值去查询数据库
 	$sponsor = $this->db->get_where("db_magento_sponsor","ms_source='{$value[0]}'")->result_array();
 	if($sponsor[0]['ms_id'])
 	$ms_id=$sponsor[0]['ms_id'];
    else
    	continue;
    $ms_number_transactions = $sponsor[0]['ms_number_transactions'];
    $ms_income = $sponsor[0]['ms_income'];
    $ms_rmb_income = $sponsor[0]['ms_rmb_income'];
    if(is_null($ms_number_transactions)) $ms_number_transactions = 0;
    if(is_null($ms_income)) $ms_income = 0;
    if(is_null($ms_rmb_income)) $ms_rmb_income = 0;
    $ms_number_transactions+=$value[8];
    $income=$value[9];
    if($ms_income_currency == 'USD') $income=substr($income, 3);
    $msi_income=$income;
    $ms_income += $income;
    $ms_rmb_income += $income*$exchangerate;
    $data=array();
    $data['ms_income_currency'] = $ms_income_currency;
    $data['ms_number_transactions'] = $ms_number_transactions;
    $data['ms_income'] = $ms_income;
    $data['ms_rmb_income'] = $ms_rmb_income;
    $this->db->update('db_magento_sponsor',$data,"ms_id='".$ms_id."'");
    $data1['ms_income_currency'] = $ms_income_currency;
    $data1['ms_number_transactions'] = $value[8];
    $data1['ms_income'] = $msi_income;
    $data1['ms_rmb_income'] = $msi_income*$exchangerate;;
    $data1['timedata'] = $timedata;
    $data1['ms_id'] = $ms_id;
    $data1['ms_source'] = $value[0];
    $data1['ms_object_name']=$sponsor[0]['ms_object_name'];
    $data1['ms_user']=$sponsor[0]['ms_user'];
     $this->db->insert("db_magento_sponsor_income",$data1);
 } 

}

//上传返图
public function savedoupload(){

   		$ms_id = $this->input->post('ms_id');
        //获取原有图片存储信息，
        $data_img = $this->db->get_where("db_magento_sponsor","ms_id='".$ms_id."'")->result_array();
        $ms_img_data=json_decode($data_img[0]['ms_img_data'],true);
        if(!is_array($ms_img_data)) $ms_img_data=array();
   		//文件保存地址
		$upload_path = 'uploads/magento_sponsor/'.date("Ymd")."/".$ms_id;
		$dir = dirname(__FILE__) . "/../../".$upload_path;
		!is_dir($dir) && @mkdir($dir, 0755, true);
		$this->db->trans_begin();
		$msg = $this->fun->uploadfile($upload_path,$ms_id,'magento_sponsor');
		if($msg["st"] == 200)
		{
			$filename = $msg["filename"];
			$nums = count($filename);
			$into['ms_img_data']=json_encode(array_merge($ms_img_data,$filename));
			$this->db->update('db_magento_sponsor',$into,"ms_id='".$ms_id."'");
			// for($i=1;$i<=$nums;$i++)
			// {
			// 	$imgdata["ms_id"] = $ms_id;
			// 	$imgdata["images_type"] = 1;
			// 	$imgdata["images_url"] = $msg["filename"][$i][0];
			// 	$imgdata["local_url"] = $msg["filename"][$i][2];
			// 	$imgdata["filename"] = $msg["filename"][$i][0];
			// 	$imgdata["filesize"] = $msg["filename"][$i][1];
			// 	$imgdata["thumb_url"] = $msg["filename"][$i][3];
			// 	$imgdata["createUser"] = $_COOKIE["username"];
			// 	$imgdata["instime"] = time();
			// 	if($msg["filename"][$i][0]!=3000003)
			// 	{
					
			// 		$this->db->query($this->db->insert_string('db_sponsor_images', $imgdata));
			// 	}
			// }

			//$this->fun->goods_update_log($ms_id,'更新商品图片',1);	//更新商品信息
			if ($this->db->trans_status() === FALSE)
			{
				$this->db->trans_rollback();
			}
			else
			{
				$this->db->trans_commit();
			}
		}
		if($msg["st"] != 200){
			return $msg;
		}else{
			$url="/magento/ajaxbutton?op=creatsponsor&type=1&id={$ms_id}&rand=".rand(0,1000);
			$imsg=array('st'=>200,'url'=>$url);
			return $imsg;
		}

		//return $msg;


}

//删除图片
public function deleteimg($id,$key){
	$data_img = $this->db->get_where("db_magento_sponsor","ms_id='".$id."'")->result_array();
	$ms_img_data=json_decode($data_img[0]['ms_img_data'],true);

	//删除服务器文件
	$img = $ms_img_data[$key];
	$path2=dirname(__FILE__) .'/../../'.$img[2];
	$path3=dirname(__FILE__) .'/../../'.$img[3];
    //return $path2;
	@unlink($path2);
	@unlink($path3);
	//删除数据库信息，
	unset($ms_img_data[$key]);
	$into['ms_img_data'] = json_encode($ms_img_data);
	$this->db->update('db_magento_sponsor',$into,"ms_id='".$id."'");
    return "ok";
}

//审核通过
public function examination($id,$type){
	$inarr=array('ms_status'=>2);
	 $this->db->update('db_magento_sponsor',$inarr,"ms_id='".$id."'");
     $this->createorder($id);
}

//统计赞助转化成功的数据
public function successdata($ms_user,$ms_object_name,$ms_source,$timedata){
     $sql="select * from `db_magento_sponsor_income`";
     $sql.=" WHERE";
        if($ms_user != '') $sql .= " `ms_user` like '%{$ms_user}%' AND";
        if($ms_object_name != '') $sql .= " `ms_object_name` like '%{$ms_object_name}%' AND";
        if($ms_source != '') $sql .= " `ms_source` like '%{$purpose}%' AND";
        if($timedata != '') $sql .= " `timedata` = '{$timedata}' AND";
      $sql .= " `ms_id` != ''";
     return $this->db->query($sql)->result_array();

}
//获取表中时间段
public function get_db_magento_sponsor_income(){
	$sql="select * from `db_magento_sponsor_income` GROUP BY `timedata`;";
	 $list=$this->db->query($sql)->result_array();
	 $data=array();
	 foreach ($list as $value) {
	 	$data[]=$value['timedata'];
	 }
	 return $data;
}



public function createorder($id){
  $sql="select * from db_magento_sponsor where ms_id='{$id}';";
  $list=$this->db->query($sql)->result_array();
  $this->load->library('Amazondata');
  //赞助店铺平台为magento shopid为72
  foreach ($list as $value) {
//付费广告和工作外包，不创建订单
            if ($value['ms_type'] == 1 || $value['ms_type'] == 4) {
            	continue;
            }
//查询订单是否已被导入
			
			$sql = "SELECT * FROM db_order_list WHERE order_sn='".$value['order_sn']."' AND shopid='72'";
			$rorder = $this->db->get_one($sql);
			if($rorder)
			{
				continue;
			}


  	//准备插入信息
            $postdata="";
            $order_sn= $this->amazondata->getNo();
			$postdata["order_sn"] = $order_sn;
			$postdata["dates"] = date("Y-m-d");
			$postdata["order_status"] = 2;
			$postdata["order_source"] ='正常订单';
			$postdata['shipping_status']=0;
			$postdata["customerid"] =addslashes(trim($value['ms_object_name']));
			
			$postdata["consignee"] =addslashes($value['ms_object_name']);
			$postdata["country"] =addslashes($value['ms_object_country']);
			$rscode = $this->db->get_where("d_country","countrynamecn='".$value['ms_object_country']."'")->result_array();
            if(isset($rscode[0]["id"])){
				$postdata["country_code"] = $rscode[0]["countryid"];
			}else{
				$postdata["country_code"]='';
			}
			$rscountry = $this->db->get_where("d_chinaexpress","NAME='".$value['ms_object_country']."'")->result_array();
			if(isset($rscountry[0]["id"])){
				$postdata["country_cn"] = $rscountry[0]["FILED1"];
			}else{
				$postdata["country_cn"]='';
			}

			$postdata["province"] = addslashes(trim($value['ms_object_state']));
			$postdata["city"] = addslashes(trim($value['ms_object_city']));
			$postdata["address"] = addslashes(trim($value['ms_object_address']));
			$postdata["address2"] ='';
			$postdata["zipcode"] = $value['ms_object_post_code'];
			$postdata["tel"] = $value['ms_object_tp'];
			$postdata["mobile"] ='';
			$postdata["email"] = $value['ms_object_email'];
			$postdata["shopid"] = '72';
			$rshop = $this->db->get_where("d_shop","id='72'")->result_array();
			$postdata["shopname"] = $rshop[0]["name"];
			$postdata["shopoper"] = $rshop[0]["updateoper"];
			
			$postdata["moneytype"] =$value['ms_object_money_sign'];
			$exchange=$this->db->get_where("d_moneyrate","name='{$value['ms_object_money_sign']}'")->result_array();
			$exchangerate=$exchange[0]["rate"];
			//$postdata["tradeid"] = $TransactionID;
			$postdata["tradeid"] =  $order_sn;
			$postdata["postageservice"] = NULL;
			$postdata['shipping_id']='';
			$postdata['shipping_name']='';
			$postdata['shipping_time']='';
			$postdata["goods_originask"] =0;//订单原始金额
			$postdata["goods_amount"] =0;//订单rmb
			$postdata["shipping_fee"] = 0;//运费rmb
			$postdata["shipping_originask"] = 0;//运费原始金额
			$postdata["add_time"] = time();
			$postdata["ordertime"] = $value['ms_creat_time'];
			$postdata["saleschannel"] = 'magento';
			$postdata["pay_fee"] = 0;
			$postdata['pack_fee']='';
			$postdata["platform_fee"] =0;
			$postdata["surplus"]="";
			$postdata["paypalmail"]='';
			$postdata['platformID']  = $rshop[0]['platfrom'];//平台
			$postdata['moneyrate']  = $exchangerate;//汇率
			$postdata["payid"]=null;
			//$postdata["platform_message"]=gettype($value['comment'])=='array'?'':$value['comment'];
		   
		    $postdata["payaccount"]='';
	$this->db->trans_begin();
			try{
				$this->db->insert("db_order_list",$postdata);

				$orderID = $this->db->insert_id();

				$factorycode =$this->amazondata->factorycode();
				$weight = 0;
				// foreach($sell as $key=>$res)
				// {
				
				$skuarr=array();
				$qtyarr=array();
				if(!empty($value['ms_product_info'])){
					$p1=explode('+',$value['ms_product_info']);
				foreach ($p1 as $va) {
					if(strpos($va,',') === false){
                     $skuarr[]=$va;
                     $qtyarr[]=1;
					}else{
					unset($p2);
					$p2=explode(',', $va);
					$skuarr[]=$p2[0];
					$qtyarr[]=$p2[1];
					}
				}

				}
				

				$skui=0;
					foreach ($skuarr as $key =>$sku) {
						$sku=trim($sku);
					$rgoods = $this->db->get_where("db_goods","goods_sku='".$sku."'")->result_array();
					
					if(isset($rgoods[0]["goods_id"]))
					{
						$goods_id = $rgoods[0]["goods_id"];
						$sweight = $qtyarr[$skui]* $rgoods[0]["g_weight"];
						$weight = $weight+$sweight;
						$costprice = 0;
						/*****************成本价计算方式********
						**  11、12开头定制的衣服按成本价计算
						**  批量的sku 按关联价计算
						**  外采购的衣服按成本价计算
						*********************************/
						if(is_numeric($sku) && preg_match('|^\d{8}$|',$sku))	//数字并且8位SKU并且11 12开头
						{
							$goodscode  = substr($sku,0,2);//取开头2位数
							if(in_array($goodscode,$factorycode))	//是否存在在工厂code
							{
								$costprice = $rgoods[0]["g_costprice"];	//定制衣服按成本价计算
							}
						}else{
							//如果当前SKU不是8位，查询父SKU是不是8位并且11，12开头
							if(is_numeric($rgoods[0]["goods_parent_sku"]) && preg_match('|^\d{8}$|',$rgoods[0]["goods_parent_sku"]))	//数字并且8位SKU并且11 12开头
							{
								$goodscodes  = substr($rgoods[0]["goods_parent_sku"],0,2);//取开头2位数
								if(in_array($goodscodes,$factorycode))	//是否存在在工厂code
								{
									$costprice = $rgoods[0]["bulkprice"];	//批量按关联价计算
								}
							}else{
								$costprice = $rgoods[0]["g_costprice"];
							}
						}
						



					}else{
						$goods_id = 0 ;
						$costprice = 0;
					}
					$postsell = "";
					$postsell["order_id"] = $orderID;
					$postsell["goods_id"] = $goods_id;
					$postsell["goods_name"] = addslashes($rgoods[0]['goods_name']);
					$postsell["goods_sn"] =  $sku;
					$postsell["costprice"] =$costprice;
					$postsell["goods_number"] = $qtyarr[$skui];
					$postsell["goods_price"] = 0;
					$postsell["goods_weight"]=$weight;
					$postsell["goods_amount"] = 0;
					$postsell["originsellprice"] = 0;
					$postsell["originsku"] = $sku;
					$postsell["product_link"]='';
					//$postsell["sale_remark"]='';
					$this->db->insert("db_order_sell",$postsell);

					if($goods_id==0)
					{
						$this->db->update("db_order_list",array("order_status"=>7),"order_id=".$orderID);
					}
					if($weight)
					{
						$this->db->update("db_order_list",array("orderweight"=>$weight),"order_id=".$orderID);
					}
					$skui++;
				 }
                //更新日志
				$imgdata["goods_id"] = $orderID;	//订单ID
				$imgdata["updatetime"] = date("Y-m-d H:i:s");
				$imgdata["createUid"] = 0;
				$imgdata["types"] = 3;
				$imgdata["content"] = 'magento赞助自动新增订单,交易ID='.$order_sn;
				$imgdata["createUser"] ='auto';
				$this->db->query($this->db->insert_string('db_goods_log', $imgdata));
				
				//更新赞助表
				$sql11="update db_magento_sponsor set order_sn= '{$order_sn}',order_id='{$orderID}' where ms_id='{$id}';";
	            $this->db->query($sql11);
 

				$this->db->trans_commit();
			}catch (Exception $e){
				$this->db->trans_rollback();
				$msg =  $e->getMessage();
				print_r($msg);exit;
			}




  }

}


}


?>